import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
    appliedCoupon: null,
    selectedIds: []
  }),
  
  getters: {
    totalItems: (state) => state.items.reduce((total, item) => total + item.quantity, 0),
    totalPrice: (state) => state.items.reduce((total, item) => total + (item.price * item.quantity), 0),
    total: (state) => state.items.reduce((total, item) => total + item.total, 0),
    subtotal: (state) => state.items.reduce((sum, item) => sum + (item.price * item.quantity), 0),
    serviceFee() {
      const s = this.subtotal
      return Math.max(s * 0.02, 5)
    },
    couponDiscount: (state) => state.appliedCoupon?.discount || 0,
    finalTotal() {
      return Math.max(this.subtotal + this.serviceFee - this.couponDiscount, 0)
    }
  },
  
  actions: {
    persist() {
      try {
        localStorage.setItem('cart', JSON.stringify({
          items: this.items,
          appliedCoupon: this.appliedCoupon
        }))
      } catch (_) {}
    },
    initCart() {
      try {
        const raw = localStorage.getItem('cart')
        if (raw) {
          const data = JSON.parse(raw)
          this.items = Array.isArray(data.items) ? data.items : []
          this.appliedCoupon = data.appliedCoupon || null
        }
      } catch (_) {}
    },
    addItem(item) {
      // 规范化入参，避免缺失字段导致 NaN 或渲染错误
      const qty = Number(item?.quantity) > 0 ? Number(item.quantity) : 1
      const normalized = {
        id: item.id ?? Date.now(),
        eventId: item.eventId ?? item.event?.id ?? null,
        eventTitle: item.eventTitle ?? item.title ?? '演出',
        venue: item.venue ?? '',
        date: item.date ?? item.eventDate ?? '',
        ticketType: item.ticketType ?? '未选择',
        seatArea: item.seatArea ?? '',
        seats: Array.isArray(item.seats) ? item.seats : [],
        price: Number(item.price) || 0,
        quantity: qty,
        image: item.image ?? item.event?.image ?? null,
        posterUrl: item.posterUrl ?? item.event?.posterUrl ?? null
      }
      const existingItem = this.items.find(i => 
        i.eventId === normalized.eventId && 
        i.ticketType === normalized.ticketType &&
        JSON.stringify(i.seats) === JSON.stringify(normalized.seats)
      )
      if (existingItem) {
        existingItem.quantity += normalized.quantity
        existingItem.total = existingItem.price * existingItem.quantity
      } else {
        this.items.push({ 
          ...normalized,
          total: normalized.price * normalized.quantity
        })
      }
      this.persist()
    },
    
    removeItem(itemId) {
      const index = this.items.findIndex(item => item.id === itemId)
      if (index > -1) {
        this.items.splice(index, 1)
      }
      this.persist()
    },
    
    removeItems(ids) {
      if (!Array.isArray(ids) || ids.length === 0) return
      const idSet = new Set(ids)
      this.items = this.items.filter(item => !idSet.has(item.id))
      this.persist()
    },
    
    updateQuantity(itemId, newQuantity) {
      const item = this.items.find(item => item.id === itemId)
      if (item && newQuantity > 0) {
        item.quantity = newQuantity
        item.total = item.price * item.quantity
      }
      this.persist()
    },
    
    clearCart() {
      this.items = []
      this.appliedCoupon = null
      this.persist()
    },
    
    applyCoupon(coupon) {
      this.appliedCoupon = coupon
      this.persist()
    },
    
    removeCoupon() {
      this.appliedCoupon = null
      this.persist()
    },
    
    // 选择功能
    selectItem(itemId) {
      if (!this.selectedIds.includes(itemId)) {
        this.selectedIds.push(itemId)
      }
    },
    
    unselectItem(itemId) {
      const index = this.selectedIds.indexOf(itemId)
      if (index > -1) {
        this.selectedIds.splice(index, 1)
      }
    },
    
    selectAll() {
      this.selectedIds = this.items.map(item => item.id)
    },
    
    clearSelection() {
      this.selectedIds = []
    },
    
    toggleSelection(itemId) {
      if (this.selectedIds.includes(itemId)) {
        this.unselectItem(itemId)
      } else {
        this.selectItem(itemId)
      }
    },
    
    // 添加测试数据（仅用于开发测试）
    addTestData() {
      if (this.items.length === 0) {
        const testItems = [
          {
            id: 'test-1',
            eventId: 1,
            eventTitle: '歌剧魅影',
            ticketType: 'VIP',
            price: 680,
            quantity: 2,
            total: 1360,
            seats: ['A1', 'A2'],
            eventDate: '2024-12-25',
            eventTime: '19:30',
            venue: '上海大剧院'
          },
          {
            id: 'test-2',
            eventId: 2,
            eventTitle: '狮子王音乐剧',
            ticketType: '一等座',
            price: 480,
            quantity: 1,
            total: 480,
            seats: ['B5'],
            eventDate: '2024-12-28',
            eventTime: '14:30',
            venue: '北京天桥艺术中心'
          },
          {
            id: 'test-3',
            eventId: 3,
            eventTitle: '周杰伦演唱会',
            ticketType: '内场',
            price: 1280,
            quantity: 3,
            total: 3840,
            seats: ['C10', 'C11', 'C12'],
            eventDate: '2024-12-30',
            eventTime: '20:00',
            venue: '鸟巢体育场'
          }
        ]
        
        this.items = testItems
        this.persist()
      }
    }
  }
})